#include "controller.h"
#include "worker.h"

Controller::Controller(QObject *parent) : QObject(parent)
{
    {
    // 创建worker对象，并且将其事件循环全部交给workerThread对象来处理，最后启动该线程，然后触发其事件处理函数。

    Worker *worker = new Worker; // 描述任务
       //调用moveToThread将该任务交给workThread
       worker->moveToThread(&workerThread);
       //operate信号发射后启动线程工作
       connect(this, SIGNAL(operate(const int)), worker, SLOT(doWork(int)));
       //该线程结束时销毁
       connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
       //线程结束后发送信号，对结果进行处理
       connect(worker, SIGNAL(resultReady(int)), this, SLOT(handleResults(int)));
       //启动线程
       workerThread.start();
       //发射信号，开始执行
       qDebug()<<"emit the signal to execute!---------------------------------";
       qDebug()<<"     current thread ID:"<<QThread::currentThreadId()<<'\n';
       emit operate(0);
     }

       {
           myThrd = new MyThread;
              connect(myThrd,&MyThread::myThreadSignal,this,&Controller::handleResults);
//              //该线程结束时销毁
//              connect(myThrd, &QThread::finished, this, &QObject::deleteLater);
              connect(this,&Controller::operate,myThrd,&MyThread::myThreadSlot);
              //启动该线程
              myThrd->start();
              QThread::sleep(5);
              emit operate(999);
       }
}

Controller::~Controller()
{
    {
    // 调用quit()函数结束线程
    workerThread.quit();
        workerThread.wait();
    }

    {
        myThrd->quit();
           myThrd->wait();
           delete myThrd;
    }
}
